import React, {useCallback, useEffect, useRef, useState} from 'react';
import NavBar from "./components/NavBar";
import Tabs from "./components/Tabs";
import Category from "./components/Category";
import BannerImage from './assets/banner.png'
import FooterImage from './assets/footer.jpg'
import styles from './styles.module.scss'
import {dataSource} from "./constants/data";
import classNames from "classnames";
import { debounce } from 'lodash'

const isInView = (el: HTMLVideoElement) => {
  const { left,right, top,bottom } = el.getBoundingClientRect()
  // 水平方向
  const isHorizontalInView = 0 < left && right < window.innerWidth
  // 竖直方向
  const isVerticalInView = top < window.innerHeight / 2 && window.innerHeight / 2 < bottom
    // 最终结果
  return isHorizontalInView && isVerticalInView

}
function App() {
    const oldYRef = useRef<number>(0)
    const contentRef = useRef<HTMLDivElement>(null)
    const [hidden,setHidden] = useState<boolean>(false)
    const playingIds = useRef<string[]>([])
    const isScrolling = useRef<boolean>(false)
    const playAll = (ids: string[]) => {
        if (ids.length === 0) {
            return ;
        }
        const videoNodeList: (HTMLVideoElement|null)[]  = ids.map(id => document.querySelector(`[data-video-id="${id}"]`))
        const videoEls = Array.from(videoNodeList)
        videoEls.forEach(videoEl => videoEl?.play());
        playingIds.current = ids;
    }
    const stopAll = (ids: string[]) =>{
        if (ids.length === 0) {
            return ;
        }
        const videoNodeList: (HTMLVideoElement | null) []  = ids.map(id => document.querySelector(`[data-video-id="${id}"]`))
        const videoEls = Array.from(videoNodeList)
        videoEls.forEach(videoEl => {
            if (videoEl) {
                videoEl.pause()
                videoEl.currentTime = 0
            }
        })

    }
    const pauseAll = (ids: string[]) => {
        if (ids.length === 0) {
            return ;
        }
        const videoNodeList: (HTMLVideoElement | null) []  = ids.map(id => document.querySelector(`[data-video-id="${id}"]`))
        const videoEls = Array.from(videoNodeList)
        videoEls.forEach(videoEl => {
            if (videoEl) {
                videoEl.pause()
            }
        })
    }

    // const x = debounce(() => {
    //     console.log('end')
    //     isScrolling.current = false
    // },500)
    const onScrollEnd = useCallback(debounce(() =>{
        const videoEls: HTMLVideoElement[] = Array.from(document.querySelectorAll('video'))
        // 找到命中的视频
        const inViewVideEls = videoEls.filter(videoEl => isInView(videoEl))

        if (inViewVideEls.length > 0) {
            const ids: (string|null)[] = inViewVideEls.map(videoEl => videoEl.getAttribute('data-video-id') || '')
            const stopIds = playingIds.current.filter(id => !ids.includes(id))
            playAll(ids as string[])
            stopAll(stopIds as string[])
        } else {
            playAll(playingIds.current)
        }
        isScrolling.current = false
    },500),[])

    const onScroll = () => {
        if (!isScrolling.current) {
            pauseAll(playingIds.current)
        }
        isScrolling.current = true
        if (contentRef.current) {
            const { top:newY } = contentRef.current.getBoundingClientRect()
            const delta = newY - oldYRef.current
            oldYRef.current = newY
            setHidden(delta < 0)
        }
         //停下超过500ms，则认为scroll end
        onScrollEnd()
    }

    useEffect(() => {
        const initVideoIds = dataSource.hot.list.slice(0,2).map(videoData => videoData.id);
        playAll(initVideoIds);
    },[])

    return (
        <div className={styles.app}>
            <header className={classNames(styles.header,{ [styles.hidden]: hidden })}>
                <NavBar title="首页 "/>
                <Tabs/>
            </header>
            {/*<div className={styles.line}></div>*/}

            <div className={classNames(styles.scrollView,{ [styles.scrolling]: hidden})} onScroll={onScroll}>
                <img className={styles.banner} src={BannerImage} alt="banner"/>

                <div ref={contentRef} className={styles.content}>
                    <h2>{dataSource.hot.title}</h2>
                    <Category onScroll={onScroll} list={dataSource.hot.list}/>

                    <h2>{dataSource.live.title}</h2>
                    <Category onScroll={onScroll}  list={dataSource.live.list}/>

                    <h2>{dataSource.recommend.title}</h2>
                    <Category onScroll={onScroll}  list={dataSource.recommend.list}/>
                </div>

                <img className={styles.banner} src={FooterImage} alt="footer"/>

                <footer className={styles.footer}>
                    <span>@Bilibili 2022</span>
                </footer>
            </div>
        </div>
    );
}

export default App;
